package com.example.exception;

import cn.dev33.satoken.util.SaResult;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.multipart.MaxUploadSizeExceededException;

import static com.example.common.StatusCodes.SYSTEM_DATABASE_MYSQL_EXCEPTION_MSG;

/**
 * Author: Zeran
 * Date: 2024-06-08 21:18
 * Desc: 使用spring的aop进行拦截处理异常
 */
@RestControllerAdvice
@Slf4j
public class GlobeExceptionHandler {
	/**
	 * 自定义抛出异常
	 */
	@ExceptionHandler(ServiceException.class)
	public SaResult handlerServiceException(ServiceException e) {
		// log.error("自定义异常：", e);
		return SaResult.error(e.getMessage());
	}

	/**
	 * 请求地址
	 */
	@ExceptionHandler(BadSqlGrammarException.class)
	public SaResult handleBadSqlGrammarException(BadSqlGrammarException e, HttpServletRequest request) {
		String requestURI = request.getRequestURI();
		log.error("请求地址'{}',发生SQL异常.", requestURI, e);
		return SaResult.error(SYSTEM_DATABASE_MYSQL_EXCEPTION_MSG);
	}

	/**
	 * 401 异常
	 */
	@ExceptionHandler(TokenMissingException.class)
	public ResponseEntity<SaResult> handleTokenMissingException(TokenMissingException ex) {
		SaResult saResult = SaResult.code(401).setMsg(ex.getMessage());
		return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body(saResult);
	}

	/**
	 * 文件大小超过限制
	 */
	@ExceptionHandler(MaxUploadSizeExceededException.class)
	public ResponseEntity<SaResult> handleMaxUploadSizeExceededException(MaxUploadSizeExceededException ex) {
		return ResponseEntity.status(HttpStatus.PAYLOAD_TOO_LARGE)
				.body(SaResult.code(413).setMsg("文件大小超过限制，最大允许上传 5MB"));
	}


	/**
	 * 处理其他未知异常（如果打开会影响security认证和鉴权）
	 */
	@ExceptionHandler(RuntimeException.class)
	public SaResult handleGlobalException(Exception e) {
		log.error("系统错误！{}", e.getMessage());
		return SaResult.error(e.getMessage());
	}
}
